package com.xzj.common.aspect;

import com.xzj.common.core.domain.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @Category com.xzj.com.xzj.basic.aspect
 * @Description 【功能描述】
 * @Author xiaj07
 * @Since 2022/11/17 14:48
 **/
@Slf4j
@Aspect
@Component
public class WebAspect {

    private final static ThreadLocal<Long> startTime = new ThreadLocal<>();

    public static void countExecuteTime(R result) {
        if (startTime.get() == null) {
            result.putExecutionTime(0L);
        } else {
            // 计算消耗的时间
            result.putExecutionTime(System.currentTimeMillis() - startTime.get());
        }
        startTime.remove();
    }

    @Pointcut("execution(public * com..controller..*(..))")
    public void pct() {
        // 只是作为一个切入点，没有实际意义
    }

    @Before("pct()")
    public void before() {
        startTime.set(System.currentTimeMillis());
    }

    @AfterReturning(returning = "result", pointcut = "pct()")
    public void doAfterReturning(R result) {
        countExecuteTime(result);
    }

}
